<template>
  <div class="columns">
    <!--文章详情-->
    <div class="column is-three-quarters">
      <!--主题-->
      <el-card
          class="box-card"
          shadow="never"
      >
        <div
            slot="header"
            class="has-text-centered"
        >
          <p class="is-size-5 has-text-weight-bold">{{ article.title }}</p>
          <div class="has-text-grey is-size-7 mt-3">
            <span>{{ dayjs(article.createTime).format('YYYY/MM/DD HH:mm:ss') }}</span>
            <el-divider direction="vertical"/>
            <span>发布者：{{ author.alias }}</span>
            <el-divider direction="vertical"/>
            <span>查看：{{ article.view }}</span>
          </div>
        </div>

        <!--Markdown-->
        <div id="preview"/>

        <!--标签-->
        <!--        <nav class="level has-text-grey is-size-7 mt-6">-->
        <!--          <div class="level-left">-->
        <!--            <p class="level-item">-->
        <!--              <b-taglist>-->
        <!--                <router-link-->
        <!--                    v-for="(tag, index) in tags"-->
        <!--                    :key="index"-->
        <!--                    :to="{ name: 'tag', params: { name: tag.name } }"-->
        <!--                >-->
        <!--                  <b-tag type="is-info is-light mr-1">-->
        <!--                    {{ "#" + tag.name }}-->
        <!--                  </b-tag>-->
        <!--                </router-link>-->
        <!--              </b-taglist>-->
        <!--            </p>-->
        <!--          </div>-->


        <!--          <div-->
        <!--              v-if="token && user.id === topicUser.id"-->
        <!--              class="level-right"-->
        <!--          >-->
        <!--            <router-link-->
        <!--                class="level-item"-->
        <!--                :to="{name:'topic-edit',params: {id:topic.id}}"-->
        <!--            >-->
        <!--              <span class="tag">编辑</span>-->
        <!--            </router-link>-->
        <!--            <a class="level-item">-->
        <!--              <span-->
        <!--                  class="tag"-->
        <!--                  @click="handleDelete(topic.id)"-->
        <!--              >删除</span>-->
        <!--            </a>-->
        <!--          </div>-->
        <!--        </nav>-->
      </el-card>

      <!--      <lv-comments :slug="topic.id"/>-->
      <div id="vditor"/>
      <el-row>
        <el-button type="primary" style="margin-top: 20px" @click="submitComment">评论</el-button>
      </el-row>
      <el-row style="margin-top: 40px">
        <el-pagination
            background
            layout="prev, pager, next"
            :total="pagination.total"
            :page-size="pagination.pageSize"
            :current-page="pagination.pageNum"

            @current-change="pageChange">
        </el-pagination>

        <article class="media" v-for="comment in comments">
<!--          <figure class="media-left image is-48x48">-->
<!--            <img :src="comment.avatar"/>-->
<!--          </figure>-->
          <div class="media-content">
            <div class="content">
              <p>
                <strong>{{ comment.username }}</strong>
                <small class="ml-2">{{ comment.createTime | date }}</small>
                <br/>
                {{ comment.content }}
              </p>
            </div>
          </div>
        </article>
      </el-row>

    </div>


    <div class="column">
      <!--作者-->
      <Author
          v-if="flag"
          :user="author"
      />
      <!--推荐-->
      <!--      <recommend-->
      <!--          v-if="flag"-->
      <!--          :topic-id="this.id"-->
      <!--      />-->
    </div>
  </div>
</template>

<script>
import {deleteTopic, getTopic} from '@/api/post'
import {mapGetters} from 'vuex'
import Author from '@/views/post/Author'
import Recommend from '@/views/post/Recommend'
import LvComments from '@/components/Comment/Comments'
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import {getArticle} from "@/api/article";
import {findById, getInfoById} from "@/api/user";
import {getTagsByArticleId} from "@/api/tag";
import {addStudyGuideCommnet, getStudyGuide, listStudyComment} from "@/api/study-guide";

export default {
  name: 'StudyGuideDetail',
  components: {Author, Recommend, LvComments},
  computed: {
    ...mapGetters([
      'token', 'user'
    ])
  },
  data() {
    return {
      comments: [],
      pagination: {
        pageNum: 1,
        pageSize: 5,
        total: 5
      },
      lastText: "",
      contentEditor: {},
      id: this.$route.params.id,
      authorId: null,
      author: {},
      article: {},
      flag: false,
      topic: {
        content: '',
        id: this.$route.params.id
      },
      tags: [],
      topicUser: {}
    }
  },
  mounted() {
    this.fetchData()
    this.setEditor()
    this.fetchComments()
  },
  methods: {
    renderMarkdown(md) {
      Vditor.preview(document.getElementById('preview'), md, {
        hljs: {style: 'github'}
      })
    },
    setEditor() {
      this.contentEditor = new Vditor('vditor', {
        height: 300,
        placeholder: '此处为评论……',
        theme: 'classic',
        upload: {
          url: 'http://localhost:8000/api/upload',
          accept: 'image/*',
          headers: {
            Authorization: localStorage.getItem('Authorization')
          },
          fieldName: 'file',
          success: (editor, msg) => {
            console.log(msg)
            let res = JSON.parse(msg)
            const fileName = res.data.fileName;
            let imageurl = 'http://localhost:8000/api/image/' + fileName
            this.contentEditor.insertValue(`![image](${imageurl})`);
          },
        },
        counter: {
          enable: true,
          type: 'markdown'
        },
        preview: {
          delay: 0,
          hljs: {
            style: 'monokai',
            lineNumber: true
          }
        },
        tab: '\t',
        typewriterMode: true,
        toolbarConfig: {
          pin: true
        },
        cache: {
          enable: false
        },
        mode: 'sv'
      })
    },
    async fetchData() {
      await this.fetchArticle()
    },
    async fetchArticle() {
      getStudyGuide(this.id).then(res => {
        this.article = res.data
        this.authorId = this.article.userId
        this.renderMarkdown(this.article.content)
        this.fetchAuthor()
      })
    },
    async fetchAuthor() {
      getInfoById(this.authorId).then(res => {
        this.author = res.data
        this.flag = true
      })
    },
    pageChange(currentPage) {
      this.pagination.pageNum = currentPage

    },
    submitComment() {
      if (this.contentEditor.getValue() === this.lastText) {
        this.$message.warning('请不要重复提交！')
        return;
      }
      let data = {
        'studyGuideId': this.article.id,
        'content': this.contentEditor.getValue()

      }
      addStudyGuideCommnet(data).then(res => {
        if (res !== undefined) {
          this.$message.success("评论成功！")
          this.lastText = this.contentEditor.getValue()
        }
      })
    },
    fetchComments() {
      listStudyComment(this.id, this.pagination.pageNum, this.pagination.pageSize).then(res => {
        this.comments = res.data.data
        for (let i = 0; i < this.comments.length; i++) {
          getInfoById(this.comments[i].userId).then(res=>{
            this.comments[i].username=res.data.username
            this.comments[i].avatar=res.data.avatar
            console.log(this.comments[i].avatar)
          })
        }
        this.pagination.total = res.data.total

      })
    },
    handleDelete(id) {
      deleteTopic(id).then(value => {
        const {code, message} = value
        alert(message)

        if (code === 200) {
          setTimeout(() => {
            this.$router.push({path: '/'})
          }, 500)
        }
      })
    }
  }
}
</script>

<style>
#preview {
  min-height: 300px;
}
</style>
